/**
 * Created by yindume on 2018/12/10.
 */
var express = require('express');
var router = express.Router();
var db = require('../../../libs/mysql');
//统一返回格式
var res_Data;
router.use( function(req, res, next) {
    res_Data = {
        code: 0,
        message: ''
    }
    next();
});
router.get('/',function (req,res) {
    var id = req.query.id || '';
    db.query(`select * from category where id='${id}'`,(err,data)=>{
        if(err){
            res.send('分类修改').end();
        }else {
            res.render('admin/category/edit', {
                userInfo:req.userInfo,
                category:data[0]
            });
        }
    })
});

router.post('/',function(req,res){
    var id = req.body.id;
    var name = req.body.name;
    db.query(`SELECT 1 FROM category WHERE name='${name}' limit 1`,(err,data)=>{
        if(err){
            res.send('验证分类相同').end();
        }else {
            if(data[0]){
                var category={
                    id:id,
                    name:name
                }
                res.render('admin/category/edit', {
                    userInfo:req.userInfo,
                    massage :'已存在相同名称的分类',
                    category:category
                });
            }else {
                db.query(`UPDATE category SET name = '${name}' WHERE id = '${id}'`,(err,data)=>{
                    if(err){
                        res.status(500).send('注册数据插入数据库失败').end();
                    }else {
                        res.redirect('/admin/category');
                    }
                })
            }
        }
    })
})


module.exports = router;